1. MongoDB Delete Operations

Definition

MongoDB provides various methods to delete documents from collections. The main delete operations are deleteOne() and deleteMany(). These operations allow you to remove documents that match specific criteria, helping you maintain and clean your database effectively.

Algorithm 1: Basic Document Deletion :-
  • Step 1: Connect to MongoDB database
  • Step 2: Select the target collection
  • Step 3: Define deletion criteria
  • Step 4: Choose delete method (deleteOne/deleteMany)
  • Step 5: Execute deletion operation
  • Example 1: Delete Single Document
    // Delete a single user by username
    db.users.deleteOne({
    username: "john_doe"
    })
    Algorithm 2: Multiple Document Deletion :-
  • Step 1: Identify deletion criteria
  • Step 2: Prepare query filter
  • Step 3: Use deleteMany() method
  • Step 4: Execute deletion
  • Step 5: Verify deleted count
  • Example 2: Delete Multiple Documents
    // Delete all expired products
    db.products.deleteMany({
    expiryDate: {
    $lt: new Date()
    }
    })
    Algorithm 3: Conditional Deletion :-
  • Step 1: Define complex conditions
  • Step 2: Combine multiple criteria
  • Step 3: Use logical operators
  • Step 4: Apply deletion operation
  • Step 5: Confirm results
  • Example 3: Conditional Delete with Multiple Criteria
    // Delete inactive users with specific criteria
    db.users.deleteMany({
    $and: [
    { lastLogin: { $lt: new Date(Date.now() - 30*24*60*60*1000) } },
    { status: "inactive" },
    { accountType: "trial" }
    ]
    })